package com.iseastar.guojiang.transfer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.app.AppCourierCaptureActivity;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.NewParcelBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.TransferTodayParcelBean;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.StringUtils;
import com.shouhuobao.take.weight.CircularImage;

import java.util.ArrayList;

import droid.frame.utils.GlideUtil;
import droid.frame.view.xlist.SListView;

/**
 * Created by lidandan on 2018/1/30.
 * 交接详情列表
 */
public class ParcelHandoverDetailsListActivity extends BaseActivity2 implements View.OnClickListener {

    private EditText mCodeET;//输入投递编号
    private Button mHandoverWarehouseBtn;
    private SListView mListView;
    private TransferTodayParcelBean item;

    private ParcelHandoverDetailsListAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        item = (TransferTodayParcelBean) getIntent().getSerializableExtra("item");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.parcel_handover_details_list);
        super.findViewById();
        getAppTitle().setCommonTitle("交接详情");
        mCodeET = (EditText) findViewById(R.id.code_et);
        mCodeET.setOnClickListener(this);
        findViewById(R.id.scan_iv).setOnClickListener(this);
        CircularImage mTitleImg = (CircularImage) findViewById(R.id.title_view);
        TextView mNameTV = (TextView) findViewById(R.id.name_tv);
        TextView mIdCardTV = (TextView) findViewById(R.id.id_card_tv);
        mListView = (SListView) findViewById(R.id.listView);
        TextView mParcelNumTV = (TextView) findViewById(R.id.parcel_num_tv);
        mHandoverWarehouseBtn = (Button) findViewById(R.id.handover_warehouse_btn);
        mHandoverWarehouseBtn.setOnClickListener(this);
        if (item != null) {
            GlideUtil.loadImage(getContext(), item.getImagePath(), null, mTitleImg);
            mNameTV.setText(item.getCourierNickName() + " (" + item.getCourierName() + ")");
            mParcelNumTV.setText("共" + item.getParcelDtos().size() + "个包裹待交接");
            mIdCardTV.setText(item.getCourierCard());
        }
        mAdapter = new ParcelHandoverDetailsListAdapter(item.getParcelDtos(), getContext(), mListView);
        mListView.setAdapter(mAdapter);

        mCodeET.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String keywords = mCodeET.getText().toString();
                    if (isEmpty(keywords)) {
                        // ignore
                        mAdapter.setItems(item.getParcelDtos(), true);
                    } else {
                        if (isNotEmpty(mCodeET.getText().toString())) {
                            mAdapter.setItems(serachParcelByBagCode(mCodeET.getText().toString()), true);
                        }
                    }
                    return true;
                }
                return false;
            }
        });
        mCodeET.addTextChangedListener(new TextWatcherExt() {
            private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 99999) {
                        String keywords = mCodeET.getText().toString();
                        if (isEmpty(keywords)) {
                            // ignore
                            mAdapter.setItems(item.getParcelDtos(), true);
                        } else {
                            if (isNotEmpty(mCodeET.getText().toString())) {
                                mAdapter.setItems(serachParcelByBagCode(mCodeET.getText().toString()), true);
                            }
                        }
                    }
                }
            };

            @Override
            public void afterTextChanged(Editable s) {
                if (isNotEmpty(s)) {
                    findViewById(R.id.bootom_view).setVisibility(View.GONE);
                } else {
                    findViewById(R.id.bootom_view).setVisibility(View.VISIBLE);
                }
                handler.removeMessages(99999);
                handler.sendEmptyMessageDelayed(99999, 500);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击输入框获取焦点
            case R.id.code_et:
                mCodeET.setFocusable(true);
                mCodeET.setFocusableInTouchMode(true);
                mCodeET.requestFocus();
                setSoftInput(mCodeET, true);
                break;
            //点击扫描投递编号
            case R.id.scan_iv:
                Intent intent = new Intent();
                intent.setClass(getContext(), AppCourierCaptureActivity.class);
                startActivityForResult(intent, Const.RequestCode.scan_bag);
                break;
            //交接入仓
            case R.id.handover_warehouse_btn:
                if (item.getParcelDtos() != null && item.getParcelDtos().size() > 0 && mAdapter.getItemsSize() == item.getParcelDtos().size()) {
                    DialogMgr.showHandoverWarehouse(getContext(), item.getParcelDtos());
                }
                break;

        }
    }

    /**
     * 更改包裹状态
     *
     * @param position
     */
    public void updateParcelStatus(int position) {
        DialogMgr.parcelHandoverDetailListPopw(getContext(), mHandoverWarehouseBtn, position, mAdapter.getItem(position));
    }

    /**
     * 操作包裹状态
     */
    public void refreshParcelStatus(int type, int position) {
        NewParcelBean bean = mAdapter.getItem(position);
        bean.setParcelStatus(type);
        mAdapter.updateItemView(position, bean);
    }

    /**
     * 交件入仓
     */
    public void handoverWarehous() {
        if (item.getParcelDtos() != null && item.getParcelDtos().size() > 0) {
            showLoadingDialog(null);
            AppHttp.getInstance().parcelHandoverWarehous(item.getParcelDtos(), item.getTaskId());
        } else {
            showToast("交件失败");
        }


    }

    /**
     * 根据投递编号搜索相应的包裹
     *
     * @param bagCode
     */
    private ArrayList<NewParcelBean> serachParcelByBagCode(String bagCode) {
        ArrayList<NewParcelBean> parcelBeans = new ArrayList<>();
        if (item != null && item.getParcelDtos() != null && item.getParcelDtos().size() > 0) {
            for (NewParcelBean bean : item.getParcelDtos()) {
                if (isNotEmpty(bean.getBagCode()) && bean.getBagCode().contains(bagCode)) {
                    parcelBeans.add(bean);
                }
            }
            return parcelBeans;
        }
        return parcelBeans;
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.parcel_handover_in_transfer:
                cancelLoadingDialog();
                ReqResult<?> result = JSON.parser(msg.obj);
                if (checkLoginStatus(result)) {
                    showToast("交接成功！");
                    finish();
                } else {
                    showToast(result.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == Const.RequestCode.scan_bag) {
            String bagcode = data.getStringExtra("result");
            if (StringUtils.isEmpty(bagcode)) {
                return;
            }
            int index = bagcode.lastIndexOf("=");
            String code2;
            if (index > -1) {
                code2 = bagcode.substring(index + 1, bagcode.length());
            } else {
                code2 = bagcode;
            }
            mCodeET.setText(code2);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

}
